package cn.zhm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;

/**
 * 屏幕截取 实现录屏区域选择
 */
public class ScreenRecording extends JWindow {
    private BufferedImage image=null;
    private int orgx, orgy, endx, endy;
    private BufferedImage tempImage=null;
    private BufferedImage saveImage=null;

    Graphics g;
    public ScreenRecording() throws AWTException{
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

        this.setBounds(0, 0, d.width, d.height);
        Robot robot = new Robot();

        image = robot.createScreenCapture(new Rectangle(0, 0, d.width,d.height));
        this.addMouseListener(new MouseAdapter() {
            @Override

            public void mousePressed(MouseEvent e) {
                orgx = e.getX();
                orgy = e.getY();
            }
            @Override

            public void mouseReleased(MouseEvent e) {

               ScreenRecording.this.getGraphics().dispose();
                g.dispose();
                ScreenRecording.this.dispose();

            }
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                endx = e.getX();

                endy = e.getY();
                Image tempImage2=createImage(ScreenRecording.this.getWidth(),ScreenRecording.this.getHeight());

                g =tempImage2.getGraphics();
                g.drawImage(tempImage, 0, 0, null);

                g.setColor(Color.CYAN);
                int x = Math.min(orgx, endx);

                int y = Math.min(orgy, endy);

                int width = Math.abs(endx - orgx)+1;

                int height = Math.abs(endy - orgy)+1;

                Start.x = x;
                Start.y = y;
                Start.width = width;
                Start.height = height;
                g.drawRect(x-1, y-1, width+1, height+1);
                try {
                    saveImage = image.getSubimage(x, y, width, height);

                    g.drawImage(saveImage, x, y, null);

                    ScreenRecording.this.getGraphics().drawImage(tempImage2,0,0,ScreenRecording.this);

                }catch (Exception ex){

                }

            }
        });
    }

    @Override

    public void paint(Graphics g) {

        RescaleOp ro = new RescaleOp(0.8f, 0, null);

        tempImage = ro.filter(image, null);

        g.drawImage(tempImage, 0, 0, this);

    }

    public static void start() {
        try {
            ScreenRecording test2 = new ScreenRecording();
            test2.setVisible(true);
        }catch (Exception e){

        }


    }
}
